<?
require "include/bittorrent.php";
require "include/benc.php";
dbconn(false);

if ($_GET["passkey"]) 
{
$passkey = sqlesc($_GET["passkey"]);
$user = mysql_fetch_row(query("SELECT COUNT(*) FROM users WHERE passkey = $passkey AND enabled = 'yes' AND parked = 'no'"));
if ($user[0] != 1)
exit();
} 
else
loggedinorreturn();

$id = (int)$_GET["id"];

if (!$id)
{
$torrents = number_format(get_row_count("torrents"));
$randnum = rand(0,$torrents-1);
$res = query("SELECT id FROM torrents");
$id = mysql_result($res, $randnum);
}

$res = query("SELECT filename, name FROM torrents WHERE id = $id") or sqlerr(__FILE__, __LINE__);
$row = mysql_fetch_assoc($res);

$fn = "$torrent_dir/$id.torrent";

if (!$row || !is_file($fn) || !is_readable($fn))
error("Unable to download torrent.");

query("UPDATE torrents SET hits = hits + 1 WHERE id = $id");

if ($CURUSER && strlen($CURUSER['passkey']) != 32) {
 $CURUSER['passkey'] = md5($CURUSER['username'].get_date_time().$CURUSER['passhash']);
 query("UPDATE users SET passkey='$CURUSER[passkey]' WHERE id=$CURUSER[id]");
}

$dict = bdec_file($fn, (1024*1024));
$dict['value']['announce']['value'] = $announce_urls[0] . "?passkey=" . ($CURUSER ? "$CURUSER[passkey]" : "$_GET[passkey]");
$dict['value']['announce']['string'] = strlen($dict['value']['announce']['value']).":".$dict['value']['announce']['value'];
$dict['value']['announce']['strlen'] = strlen($dict['value']['announce']['string']);

header('Content-Disposition: inline; filename="'.$row['filename'].'"');
header("Content-Type: application/x-bittorrent");
header('Content-Disposition: inline; filename="'.$row['filename'].'"');
print(benc($dict));
?>